#-*- coding:UTF-8 -*-

import threading, logging, time
import urllib
import urllib.request
import json

ap_server = ''
access_token = ''
header = {"User-Agent" : "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.7.62 Version/11.01",
          "Accept" : "application/json"}

class WebHelper:

    # 访问brthm.com的用户token
    userId = ''

    def __init__(self, ap_server, ap_user, ap_password):
        self.ap_server = ap_server
        self.ap_user = ap_user
        self.ap_password = ap_password
        self.obtainAuthToken()

    def obtainAuthToken(self):
        global ap_server, access_token, header

        ap_server = self.ap_server

        #url = 'http://www.brthm.com/obtainAuthToken'
        url = self.ap_server + '/obtainAuthToken'
        try:
            values = {'loginName' : self.ap_user,
                      'password' : self.ap_password}
            data = urllib.parse.urlencode(values).encode("utf-8")
            req = urllib.request.Request(url, data=data, headers=header)
            response = urllib.request.urlopen(req)
            # '{"token":"access_token.getKey()","user":"1234567890"}'
            tokenjson = response.read().decode("utf-8")
            access_token = json.loads(tokenjson)['token']
            self.userId = json.loads(tokenjson)['user']
            return access_token
        except:
            return ''


def deal_require_dict(code, oldVal=None):
    '''
    http://.../dict/getDictsByCode?code=EDUCATION
    '''
    url = ap_server + '/dict/getDictsByCode'
    try:
        values = {'access_token' : access_token,
                  'code' : code }
        data = urllib.parse.urlencode(values).encode("utf-8")
        req = urllib.request.Request(url, data=data, headers=header)
        response = urllib.request.urlopen(req)
        jsonText = response.read().decode("utf-8")
        jsonObjs = json.loads(jsonText)
        dict_ = {code : [code_['code']+'//'+code_['name']  for code_ in jsonObjs]}
        return dict_
    except:
        return oldVal


if __name__ == "__main__":
    obj = WebHelper('http://www.brthm.com', 'dataisland', "dataisland")

    s = deal_require_dict('EDUCATION')
    print (s)
    '''
    {'EDUCATION': ['EDUCATIONCOLLEGE//本科', 'EDUCATIONHIGHSCHOOL//高中', 'EDUCATIONPRIMARY//小学',
    'EDUCATIONJUNIOR//初中', 'EDUCATIONDOCTOR//博士', 'EDUCATIONMASTER//硕士', 'EDUCATIONJUNIORCOLLEGE//大专']}
    '''
